<template>
  <el-dialog width="80%" @close="cancleEditTemplate" v-model="dialogVisible" title="编辑模板信息" destroy-on-close center>
    <template #default>
      <el-form :model="template" label-width="100px" label-position="left">
        <el-form-item label="*模板编号">
          <el-input v-model="template.checkTemplateId" readonly aria-placeholder="模板编号" />
        </el-form-item>
        <el-form-item label="检测项名称">
          <el-input v-model="template.checkTemplateName" aria-placeholder="检测项名称" />
        </el-form-item>
        <el-form-item label="检测项类型">
          <el-select v-model="template.checkTemplateType" placeholder="请选择模板类型">
            <el-option :value="1"  label="来料检验"/>
            <el-option :value="2"  label="首检"/>
            <el-option :value="3"  label="未检"/>
            <el-option :value="4"  label="巡检"/>
            <el-option :value="5"  label="自检"/>
            <el-option :value="6"  label="成品检验"/>
            <el-option :value="7"  label="发货检验"/>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input  type="textarea"  v-model="template.note" aria-placeholder="检测项名称" />
        </el-form-item>
      </el-form>

        <el-div>
          <el-tabs type="border-card" v-model="activeTab">
            <el-tab-pane label="检测项" name="first"></el-tab-pane>
            <el-tab-pane label="物料产品" name="second"></el-tab-pane>

            <!-- 检测项表 -->
          <el-row v-if="activeTab === 'first'" style="margin-top: 10px;">
            <el-col :span="24">
              <!-- 工具栏 -->
              <!-- 工具栏部分开始 -->
              <el-row name="first" style="margin-top: 10px;">
                <el-col :span="24">
                  <el-tooltip
                      class="box-item"
                      effect="dark"
                      content="添加检测模板"
                      placement="top-start"
                  >
                    <el-button @click="toAddDict" type="primary">
                      <el-icon>
                        <Plus/>
                      </el-icon>
                    </el-button>
                  </el-tooltip>
                  <el-button @click="editBtnHandler" :disabled="editBtnDisabledVison" type="primary">
                    <el-icon>
                      <EditPen/>
                    </el-icon>
                  </el-button>
                  <el-popconfirm confirm-button-text="是" cancel-button-text="否"
                                 @confirm="deleteBtnHandler" title="您确定要删除选中的典信息吗？">
                    <template #reference>
                      <el-button :disabled="deleteBtnDisabled" type="primary">
                        <el-icon>
                          <Minus/>
                        </el-icon>
                      </el-button>
                    </template>
                  </el-popconfirm>

                </el-col>
              </el-row>
              <!-- 工具栏部分结束 -->
              <!-- 表格 -->
              <el-table ref="flawTabel" :data="templates" @selection-change="handleCheckItemSelectionChange" border :stripe="true" style="width: 95%">
                <!-- 表格列 -->
                <el-table-column type="selection" width="55"/>
                <el-table-column prop="checkItemId" label="检测项编号"/>
                <el-table-column prop="checkItemName" label="检测项名字"/>
                <el-table-column prop="checkItemType" label="检测项类型"/>
                <el-table-column prop="checkItemTools" label="检测项工具"/>
                <el-table-column prop="checkItemMethod" label="检测项方法"/>
                <el-table-column prop="checkItemStandard" label="标准"/>
                <el-table-column prop="checkItemUnit" label="单位"/>
                <el-table-column prop="checkItemErrorUp" label="误差下限"/>
                <el-table-column prop="checkItemErrorDown" label="误差上限"/>
                <el-table-column width="140" label="操作">
                  <template #default="scope">
                    <el-button type="primary" @click="toEditTemplate(scope.row.checkItemId)" size="small">编辑</el-button>
                    <el-popconfirm confirm-button-text="是" cancel-button-text="否"
                                   @confirm="deleteTemplate(scope.row.checkItemId)" title="确定删除这个检测项吗？">
                      <template #reference>
                        <el-button type="danger" size="small">删除</el-button>
                      </template>
                    </el-popconfirm>
                  </template>
                </el-table-column>
              </el-table>
              <!-- ... -->
              <!-- 分页部分开始 -->
              <el-row style="margin-top: 10px;">
                <el-col :span="24">
                  <el-pagination background @change="pageChange" layout="prev, pager, next" v-bind:page-size="limit"
                                 :total="total"/>
                </el-col>
              </el-row>
              <!-- 分页部分结束 -->
            </el-col>
          </el-row>


              <!-- 物料产品表 -->
              <el-row v-if="activeTab === 'second'" style="margin-top: 10px;">
                <el-col :span="24">
                  <!-- 工具栏 -->
                  <!-- 工具栏部分开始 -->
                  <el-row name="first" style="margin-top: 10px;">
                    <el-col :span="24">
                      <el-tooltip
                          class="box-item"
                          effect="dark"
                          content="添加物料产品"
                          placement="top-start"
                      >
                        <el-button @click="toAddMaterialProduct" type="primary">
                          <el-icon>
                            <Plus/>
                          </el-icon>
                        </el-button>
                      </el-tooltip>
                      <el-button @click="editProductBtnHandler" :disabled="editBtnProductDisabled" type="primary">
                        <el-icon>
                          <EditPen/>
                        </el-icon>
                      </el-button>
                      <el-popconfirm confirm-button-text="是" cancel-button-text="否"
                                     @confirm="deleteProductBtnHandler" title="您确定要删除选中的信息吗？">
                        <template #reference>
                          <el-button :disabled="deleteProductBtnDisabled" type="primary">
                            <el-icon>
                              <Minus/>
                            </el-icon>
                          </el-button>
                        </template>
                      </el-popconfirm>

                    </el-col>
                  </el-row>
                  <!-- 工具栏部分结束 -->
              <!-- 表格 -->
              <el-table ref="materialProductTable" :data="materials" @selection-change="handleMaterialProductSelectionChange" border :stripe="true" style="width: 95%">
                <!-- 表格列 -->

                  <el-table-column type="selection" width="55"/>
                  <el-table-column prop="materialProductId" label="产品物料编码"/>
                  <el-table-column prop="materialProductName" label="产品物料名称"/>
                  <el-table-column prop="types" label="规格型号"/>
                  <el-table-column prop="underCheck" label="最低检测数"/>
                  <el-table-column prop="unit" label="单位"/>
                  <el-table-column prop="maxNoQualified" label="最大不合格数"/>
                  <el-table-column prop="maxFatalDefect" label="最大致命缺陷率"/>
                  <el-table-column prop="maxSeriousDefect" label="最大严重缺陷率"/>
                  <el-table-column prop="maxLittleFlaw" label="最大轻微缺陷率"/>
                  <el-table-column width="140" label="操作">
                    <template #default="scope">
                      <el-button type="primary" @click="toEditTemplate1(scope.row.materialProductId)" size="small">编辑</el-button>
                      <el-popconfirm confirm-button-text="是" cancel-button-text="否"
                                     @confirm="deleteTemplate1(scope.row.materialProductId)" title="确定删除这个物料产品吗？">
                        <template #reference>
                          <el-button type="danger" size="small">删除</el-button>
                        </template>
                      </el-popconfirm>
                    </template>
                  </el-table-column>
                </el-table>
                <!-- ... -->
                  <!-- 分页部分开始 -->
                  <el-row style="margin-top: 10px;">
                    <el-col :span="24">
                      <el-pagination background @change="pageChange1" layout="prev, pager, next" v-bind:page-size="limit"
                                     :total="total"/>
                    </el-col>
                  </el-row>
                  <!-- 分页部分结束 -->
            </el-col>
          </el-row>


          </el-tabs>
        </el-div>

      <FlawdictAddtotemplateWin :visible="templateaddvis" :checkTemplateId="this.checkTemplateId" @optionCompleted="addTemplateItem"></FlawdictAddtotemplateWin>
      <TemplateFlawdictEditWin  :visible="editBtnDisabled" :checkItemId="checkItemId"   @optionCompleted1="editTemplateDict"></TemplateFlawdictEditWin>

      <MaterialproductAddWin :visible="materialProductAddVis" :templateId="this.checkTemplateId" @optionCompleted="addMaterialProduct"></MaterialproductAddWin>
      <MaterialproductEditWin :visible="materialProductEditVis" :materialProductId="materialProductId" @optionCompleted2="editMaterialProduct"></MaterialproductEditWin>

    </template>


    <!-- footer插槽中放两个按钮 -->
    <template #footer>
      <el-row>
        <el-col :span="12">
          <el-button type="primary" @click="editTemplate">确定</el-button>
        </el-col>
        <el-col :span="12">
          <el-button type="primary" @click="cancleEditTemplate">取消</el-button>
        </el-col>
      </el-row>
    </template>
  </el-dialog>


</template>
<script>
import { watch } from "vue";
import TemplateRequest from "@/api/checktemplate.js";
import FlawItem from "@/api/flawItem.js";
import MaterialProductRequest from "@/api/materialproduct.js";
import FlawdictAddtotemplateWin from "@/views/qc/checktemplate/flawdict-addtotemplate-win.vue";
import TemplateFlawdictEditWin from "@/views/qc/checktemplate/templateFlawdict-edit-win.vue";
import FlawItemRequest from "@/api/flawItem.js";
import MaterialproductAddWin from "@/views/qc/checktemplate/materialproduct-add-win.vue";
import MaterialproductEditWin from "@/views/qc/checktemplate/materialproduct-edit-win.vue";

export default {
  components: {
    FlawdictAddtotemplateWin,
    TemplateFlawdictEditWin,
    MaterialproductAddWin,
    MaterialproductEditWin
  },
  props: ["visible","checkTemplateId"],
  emits: ["optionCompleted"], // 对外暴露一个事件，用来传递添加学生的操作结果
  data() {
    return {
      materialProductEditVis:false,//编辑物料产品是否弹窗
      materialProductAddVis:false,//添加物料产品是否弹窗
      templateId:0,//传递的模板id

      editBtnProductDisabled:false,//编辑物料产品是否弹窗
      deleteProductBtnDisabled:false,//删除物料产品是否弹窗

      activeTab: 'first',
      queryTemplate:{},
      queryProduct:{},
      templates: [],// 绑定表格的信息
      dialogVisible: false,// 编辑学生窗口的显示与隐藏
      template: {},
      queryFlawItem:{},
      types:{},
      page:1,
      limit: 10,
      total: 0,

      limit1: 10,
      total1:0,
      page1:1,

      checkItemId:"",
      materialProductId:undefined,


      flawTempID:0,
      editBtnDisabled:false,//编辑检测的模板是否弹窗


      materials:[],

      templateaddvis:false,//添加检测的模板是否显示

      editBtnDisabledVison:false,//编辑检测的模板是否显示
      deleteBtnDisabled:false,




    }
  }, methods: {
    findSearch(){},

    /**
     * 工具类的批量删除
     */
    deleteProductBtnHandler(){
        let selectionRows = this.$refs.materialProductTable.getSelectionRows();
        let MaterialProductIds = new Array();
        selectionRows.forEach(row => {
          MaterialProductIds.push(row.materialProductId);
        })
        MaterialProductRequest.deleteMaterialProducts(MaterialProductIds, res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.loadMaterialProduct();
        });
    },


    /**
     * 监听物料产品表格的选中事件
     */
    handleMaterialProductSelectionChange() {
      let selectionRows = this.$refs.materialProductTable.getSelectionRows();
      console.log(selectionRows)
      if (selectionRows.length == 0) {
        this.editBtnProductDisabled = true;
        this.deleteProductBtnDisabled = true;
      } else if (selectionRows.length == 1) {
        this.editBtnProductDisabled = false;
        this.deleteProductBtnDisabled = false;
      } else {
        this.editBtnProductDisabled = true;
        this.deleteProductBtnDisabled = false;
      }
    },


    /**
     * 工具栏编辑事件
     */
    editProductBtnHandler(){
      let editProduct = this.$refs.materialProductTable.getSelectionRows()[0];
      if (editProduct != undefined) {
        this.materialProductId = editProduct.materialProductId;
        this.materialProductEditVis = true;
      } else {
        this.$message({
          type: 'warning',
          message: '请选择要编辑的信息!'
        });
      }
    },

    /**
     * 监听编辑产品物料的子事件
     */
    editMaterialProduct(){
      this.materialProductEditVis = false;
      this.loadMaterialProduct();
    },

    /**
     * 监听添加产品物料的子事件
     */
    addMaterialProduct(){
      this.materialProductAddVis = false;
      this.loadMaterialProduct();
    },

    /**
     * 工具栏中的添加物料产品
     */
    toAddMaterialProduct(){
      this.materialProductAddVis = true;
      this.templateId = this.checkTemplateId;
    },

    pageChange1(currentPage, pageSize) {

    },



    /**
     * 监听表格的选中事件
     */
    handleCheckItemSelectionChange() {
      let selectionRows = this.$refs.flawTabel.getSelectionRows();
      console.log(selectionRows)
      if (selectionRows.length == 0) {
        this.editBtnDisabledVison = true;
        this.deleteBtnDisabled = true;
      } else if (selectionRows.length == 1) {
        this.editBtnDisabledVison = false;
        this.deleteBtnDisabled = false;
      } else {
        this.editBtnDisabledVison = true;
        this.deleteBtnDisabled = false;
      }
    },

    /**
     * 监听子组件编辑事件完成
     */
    editTemplateDict(){
      this.editBtnDisabled = false;
      this.loadFlawItemByTemplateId();
    },
    toAddDict(){
        this.templateaddvis = true;
        this.template.templateId = this.checkTemplateId;
    },
    /**
     * 监听子组件事件完成
     */
    addTemplateItem(){
      this.templateaddvis = false;
      this.loadFlawItemByTemplateId();
    },
    /**
     * 工具类的编辑子组件
     */
    editBtnHandler(){
      let editTemplateDict = this.$refs.flawTabel.getSelectionRows()[0];
      if (editTemplateDict != undefined) {
          this.checkItemId = editTemplateDict.checkItemId;
          this.editBtnDisabled = true;
      } else {
        this.$message({
          type: 'warning',
          message: '请选择要编辑的信息!'
        });
      }

    },
    /**
     * 检测项的工具类删除子组件
     */
    deleteBtnHandler(){
      let selectionRows = this.$refs.flawTabel.getSelectionRows();
      let checkItemIds = new Array();
      selectionRows.forEach(row => {
        checkItemIds.push(row.checkItemId);
      })
      FlawItemRequest.deleteCheckItems(checkItemIds, res => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.loadFlawItemByTemplateId();
      });
    },
    /**
     * 检测模板中检测项的行编辑事件
     */
    toEditTemplate(checkItemId){
      this.editBtnDisabled = true;
      this.checkItemId = checkItemId
    },
    /**
     * 行删除事件
     */
    deleteTemplate(checkItemId){
      FlawItem.deleteCheckItem(checkItemId, res => {
        if (res.code == '200') {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.loadFlawItemByTemplateId();
        } else {
          this.$message({
            type: 'error',
            message: '删除失败!'
          });
        }
      })
    },



    /**
     * 分页加载检测项
     * @param currentPage
     * @param pageSize
     */
      pageChange(currentPage, pageSize) {

        // 将最新的页码赋值给this.currentPage
        this.page = currentPage;
        // 重新加载数据
        this.loadFlaw();
      },


    /**
     * 分页加载产品信息
     */
    loadMaterialProduct(){
      this.queryProduct.page = this.page1;
      this.queryProduct.limit = this.limit1;
      this.queryProduct.templateId=this.checkTemplateId;
      console.log(this.queryProduct.templateId);
      MaterialProductRequest.loadMaterialProduct(this.queryProduct, res => {
        this.materials = res.data.data;
        console.log(this.materials[2])

      })
    },
    /**
     * 加载所有的缺陷项
     */
    loadFlawItemByTemplateId(){
      this.queryFlawItem.page = this.page;
      this.queryFlawItem.limit = this.limit;
      this.queryFlawItem.templateId = this.checkTemplateId;
      FlawItem.loadFlawItemByTemplateId(this.queryFlawItem.templateId, this.queryFlawItem.page, this.queryFlawItem.limit, res => {
        this.templates = res.data.data;
        this.total = res.data.total;
      });
    },


    /**
     * 取消添加学生的事件
     */
    cancleEditTemplate(){
      // 通知父组件  操作完成，让父组件关闭窗体
      this.$emit("optionCompleted");
    },
    /**
     * 添加学生信息
     */
    editTemplate(){
      TemplateRequest.updateTemplate(this.template,res=>{
        if (res.code == '200'){
          this.$message({
            type: 'success',
            message: '编辑成功!'
          });
          // 通知父组件  操作完成，让父组件关闭窗体
          this.$emit("optionCompleted");
        }else if(res.code == '300'){
          this.$message({
            type: 'warning',
            message: '字典' + (res.msg.indexOf("templateName") > 0 ?"名称":"类型") + "重复"
          });
        }else{
          this.$message({
            type: 'error',
            message: '编辑字典失败!'
          });
        }
      });
    },




    /**
     * 加载学生信息
     */
    loadTemplate(){
      TemplateRequest.getById(this.checkTemplateId,res=>{
        if(res.data != null)
          this.template = res.data;
        this.loadFlawItemByTemplateId();
        this.loadMaterialProduct();
      });
    },
    /**
     * 加载所有信息
     */
    loadTemplateAll() {
      TemplateRequest.loadTemplateAll(res => {
        const types = res.data.map(item => {
          return {
            checkTemplateType: item.checkTemplateType,
          }
        })
        let seen = {}
        let filteredArr = types.filter(item => {
          let key = item.checkTemplateType
          if (!seen[key]) {
            seen[key] = true
            return true
          }
          return false
        })
        this.types = filteredArr;
      })
    }


  }, mounted(props) {
    this.loadTemplate();
    this.loadTemplateAll();

    this.loadMaterialProduct();

    // this.loadFlawItemByTemplateId();
    // 侦听props   一旦发生变化，就会出发下面的函数
    watch(() => this.visible, (newVal, oldVal) => {
      // 将最新的值设置给弹窗的dialogVisible属性
      this.dialogVisible = newVal;
    });

    watch(() => this.checkTemplateId, (newVal, oldVal) => {
      // 如果templateId 发生变化，重新加载字典信息
      this.loadTemplate();
    });
  }
}
</script>